package com.chapter.sample.common.component;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.IntStream;

@Slf4j
public class RedisBloomFilter<T> {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据给定的布隆过滤器判断值是否存在
     */
    public void addByBloomFilter(BloomFilterHelper<T> bloomFilterHelper, String key, Set<? extends T> values) {
        Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper不能为空");
        int[] offset = values.stream().map(bloomFilterHelper::murmurHashOffset).flatMapToInt(IntStream::of).toArray();
        try {
            redisTemplate.executePipelined((RedisCallback) connection -> {
                for (int i : offset) {
                    connection.setBit(redisTemplate.getKeySerializer().serialize(key), i, true);
                }
                return null;
            });
        } catch (Exception e) {
            log.error("includeByBloomFilter msg:{}", e.getMessage(), e);
        }
    }

    /**
     * 根据给定的布隆过滤器添加值
     */
    public <T> void addByBloomFilter(BloomFilterHelper<T> bloomFilterHelper, String key, T value) {
        Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper不能为空");
        int[] offset = bloomFilterHelper.murmurHashOffset(value);
        try {
            for (int i : offset) {
                redisTemplate.opsForValue().setBit(key, i, true);
            }
        } catch (Exception e) {
            log.error("addByBloomFilter msg:{}", e.getMessage(), e);
        }
    }

    /**
     * 根据给定的布隆过滤器判断值是否存在
     */
    public <T> boolean includeByBloomFilter(BloomFilterHelper<T> bloomFilterHelper, String key, T value) {
        Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper不能为空");
        int[] offset = bloomFilterHelper.murmurHashOffset(value);
        try {
            for (int i : offset) {
                if (!redisTemplate.opsForValue().getBit(key, i)) {
                    return false;
                }
            }
        } catch (Exception e) {
            log.error("includeByBloomFilter msg:{}", e.getMessage(), e);
            return true;
        }
        return true;
    }

    /**
     * 根据给定的布隆过滤器判断值是否存在
     */
    public <R extends T> Map<R, Boolean> includeByBloomFilter(BloomFilterHelper<T> bloomFilterHelper, String key, List<R> values) {
        Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper不能为空");
        int[] offset = values.stream().map(bloomFilterHelper::murmurHashOffset).flatMapToInt(IntStream::of).toArray();
        try {
            List<Boolean> list = redisTemplate.executePipelined((RedisCallback) connection -> {
                for (int i : offset) {
                    connection.getBit(redisTemplate.getKeySerializer().serialize(key), i);
                }
                return null;
            });
            List<List<Boolean>> valuePairs = Lists.partition(list, bloomFilterHelper.getNumHashFunctions());
            Map<R, Boolean> result = Maps.newHashMapWithExpectedSize(values.size());
            for (int i = 0; i < values.size(); i++) {
                R v = values.get(i);
                result.put(v, valuePairs.get(i).stream().reduce(true, Boolean::logicalAnd));
            }
            return result;
        } catch (Exception e) {
            log.error("includeByBloomFilter msg:{}", e.getMessage(), e);
            return Collections.emptyMap();
        }
    }
}
